package bancosys.tec.exception.informer;

import static bancosys.tec.component.ComponentMessages.SYSTEM_ERROR;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.exception.ExceptionUtils;

import bancosys.tec.exception.BusinessException;
import bancosys.tec.exception.LocalizedMessageHolder;

/**
 * Helper that provides friendly messages to the a user that knows the system's business given system exceptions.
 * 
 * @author lundberg
 */
public class BusinessUserFriendlyExceptionInformer implements UserFriendlyExceptionInformer {

    /**
     * {@inheritDoc}
     */
    public List<LocalizedMessageHolder> getUserFriendlyMessages(Throwable t) {
        List<LocalizedMessageHolder> messages = new ArrayList<LocalizedMessageHolder>();
        for (LocalizedMessageHolder holder : this.getUserFriendlyMessageHolders(t)) {
            messages.add(holder);
        }
        if (messages.isEmpty()) {
            messages.add(SYSTEM_ERROR.create());
        }
        return messages;
    }

    /**
     * A list of the messages holders of all business exceptions on this exception's stack trace.
     * 
     * @param t throwable
     * @return list of localized message holders
     */
    protected List<LocalizedMessageHolder> getUserFriendlyMessageHolders(Throwable t) {
        List<LocalizedMessageHolder> holders = new ArrayList<LocalizedMessageHolder>();
        for (Throwable e : ExceptionUtils.getThrowables(t)) {
            if (e instanceof BusinessException) {
                holders.add(((BusinessException) e).getLocalizedMessageHolder());
            }
        }
        return holders;
    }
}
